package com.yjd.bi.etl.business.service;

import java.util.Calendar;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.yjd.bi.etl.comm.BaseService;
import com.yjd.bi.etl.comm.Constants;
import com.yjd.bi.etl.sql.BusinessSqlConstants;
import com.yjd.bi.etl.sql.UserSqlConstants;
import com.yjd.bi.report.model.BiDatabaseInfoModel;
import com.yjd.bi.report.util.BiUtil;
import com.yjd.comm.util.DateUtil;

@Component("transferService")
public class TransferService extends BaseService {

	private static final int DAYOFSECOND = 86400;

	public void process() throws Exception {
		BiDatabaseInfoModel model = this.getBiDatabaseInfoModel();
		JdbcTemplate jt = BiUtil.getJdbcTemplate(model);

		// 统计历史数据
		long maxDate = jt
				.queryForInt(BusinessSqlConstants.GET_MAX_TRANSFER_TATISTIC_DATE);

		if (maxDate == 0) {
			// 没有统计过，取网站上线运营的第一天 平台上线时间（2013年12月21日00：00：00）
			maxDate = Constants.INITIALIZATION_TIME;
		} else {
			maxDate = DateUtil.dateStringToTimestamp(maxDate + "",
					DateUtil.PATTERN_yyyyMMdd) + DAYOFSECOND;
		}

		// 获取当天的0点的时间戳
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		long todayTime = todayStart.getTime().getTime() / 1000L;

		while (maxDate < todayTime) {
			// 统计前一天的用户数据
			statisticLastData(maxDate, jt);
			maxDate += DAYOFSECOND;// 加一天和当前时间比较，如果小于当前时间则继续统计

		}
	}

	private void statisticLastData(long maxDate, JdbcTemplate jt) {
		long beginDate = maxDate;
		long endDate = beginDate + DAYOFSECOND - 1;
		Long staticsDate = Long.parseLong(DateUtil.timestampToDateString(
				beginDate, DateUtil.PATTERN_yyyyMMdd));
		
		/*int invest_amount = jt.queryForObject(
				BusinessSqlConstants.GET_INVEST_AMOUNT, new Object[] {
						beginDate, endDate }, Integer.class);				
		int invest_price = jt.queryForObject(
				BusinessSqlConstants.GET_INVEST_PRICE, new Object[] {
						beginDate, endDate }, Integer.class);*/

		//债权转让成交额
		double transfer_price = jt.queryForObject(
				BusinessSqlConstants.GET_TRANSFER_PRICE, new Object[] {
						beginDate, endDate }, Double.class);	
		//债权转让成交笔数
	    int transfer_amount = jt.queryForObject(
				BusinessSqlConstants.GET_TRANSFER_AMOUNT, new Object[] {
						beginDate, endDate }, Integer.class);		
		
		try {
			jt.update(BusinessSqlConstants.TRANSFER_INSERTSQL, transfer_price,
					transfer_amount, staticsDate);
		} catch (Exception e) {
			logger.info("批量处理插入失败，处理sql:"
					+ BusinessSqlConstants.INVESTINFO_INSERTSQL + "处理数据:"
					+ staticsDate + "错误信息:" + e);
		}

	}

}
